package com.mz.mattress.api.util;

import com.mz.mattress.api.redis.RedisKeys;
import com.mz.mattress.api.enums.OrderTagEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class IdUtil {

    public static final String DATE_YYMMDDHHMMSS = "yyMMddHHmmss";
    public static final String DIGIT5 = "%05d";

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATE_YYMMDDHHMMSS);

    public static Long getMemberId() {
        String str = FORMATTER.format(LocalDateTime.now()) + (10 + ThreadLocalRandom.current().nextInt(89));
        return Long.valueOf(str);
    }

    public static String generateSsn() {
        return FORMATTER.format(LocalDateTime.now()) + (100 + ThreadLocalRandom.current().nextInt(899));
    }

    /**
     * 生成Id   yyMMdd+ 00001(一天可生成10W个ID) + 90（订单标识）
     * 长度 6+2+5 = 13
     * @return
     */
    public static Long generatedCommonId(OrderTagEnum tagEnum) {
        String prefix = RedisKeys.getPrefixKey(tagEnum);

        if (SpringUtil.isTest()) {
            prefix = "9" + prefix.substring(1);
        }

        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
        Long increment = redisTemplate.opsForValue().increment(prefix);
        // 对KEY添加过期时间
        redisTemplate.opsForValue().set(prefix, increment, 3, TimeUnit.DAYS);

        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        //最多1W比订单
        if (increment.toString().length() < 5) {
            sb.append(String.format(DIGIT5, increment));
        } else {
            sb.append(increment);
        }
        return Long.valueOf(sb.toString());
    }


    public static final Map<String, AtomicInteger> dateIdMap = new HashMap<>();

    public static Long genOrderId(OrderTagEnum tagEnum, String datetime) {

        String date = datetime.substring(2, 10).replace("-", "");
        String prefix = date + tagEnum.getValue();

        AtomicInteger id = dateIdMap.get(date);
        if (id == null) {
            //100开始
//            id = new AtomicInteger(100);
            id = new AtomicInteger(1);
            dateIdMap.put(date, id);
        } else {
            id.getAndIncrement();
        }

        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        //最多1W比订单
        if (id.toString().length() < 5) {
            sb.append(String.format(DIGIT5, id.intValue()));
        } else {
            sb.append(id);
        }
        return Long.valueOf(sb.toString());
    }

    public static OrderTagEnum getOrderTag(Long orderId) {
        return getOrderTag(orderId.toString());
    }

    public static OrderTagEnum getOrderTag(String orderId) {
        String tag = orderId.substring(6, 8);
        return OrderTagEnum.valueOf(Integer.valueOf(tag));
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    private static AtomicInteger ID = new AtomicInteger(0);

    public static String generateSyncId() {
        String dateStr = FORMATTER.format(LocalDateTime.now());
        return dateStr + (100 + incrInt());
    }

    private static synchronized int incrInt() {

        int val = ID.getAndIncrement();
        if (val > 899) {
            ID.set(0);
            return 1;
        }

        return val;
    }

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 30; i++) {

            Long orderId = genOrderId(OrderTagEnum.mattressOrder, "2025-04-11 18:37:02");
            System.out.println(orderId);
        }

        for (int i = 0; i < 20; i++) {

            Long orderId = genOrderId(OrderTagEnum.mattressOrder, "2025-04-13 18:37:02");
            System.out.println(orderId);
        }

    }

}
